package com.example.webflux;

import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.http.server.reactive.HttpHandler;
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;
import reactor.netty.http.server.HttpServer;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class FluxMainApplication {

    public static void main(String[] args) throws IOException {
        /**
         * 创建处理http请求的处理器
         */
        HttpHandler httpHandler = new HttpHandler() {
            @Override
            public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) {
                /**
                 * 请求处理业务
                 */
                System.out.println(Thread.currentThread().getName()); // 获取当前线程名称
                System.out.println(request.getURI()); // 获取请求的URI
                DataBufferFactory dataBufferFactory = response.bufferFactory();// 获取缓冲工厂
                DataBuffer dataBuffer = dataBufferFactory.wrap(request.getURI().toString().getBytes(StandardCharsets.UTF_8)); // 创建数据缓冲区
                Mono<DataBuffer> mono = Mono.just(dataBuffer); // 创建Mono对象
                return response.writeWith(mono); // 响应数据
            }
        };
        /**
         * 创建适配器
         */
        ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler);
        /**
         * 创建服务器
         */
        HttpServer.create()
                .host("localhost")
                .port(8080)
                .handle(adapter)
                .bindNow(); // 绑定
        System.out.println("服务器启动");
        System.in.read();
        System.out.println("服务器关闭");
    }

}
